﻿

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using WHLRDF.Application.Model;
using WHLRDF.ORM;

namespace WHLRDF.Application.BLL
{
    /// <summary>
    /// 区域实例
    /// </summary>
    public class RegionService : SerivceBase, IRegionService
    {
        #region 基本方法
        public static string savePath
        {
            get
            {
                return  ApplicationEnvironments.BaseDirectory+ ApplicationEnvironments.ConfigPath+ "/region/region.js";
            }
        }
        /// <summary>
        /// 查询所有
        /// </summary>
        public List<RegionEntity> GetAll()
        {
            ICriterion criter = Expression.Eq(RegionEntity.__IsDeleted, false);
            return this.Query<RegionEntity>(criter).ToList();
        }
        /// <summary>
        /// 获取单个实例的方法
        /// <param name="id">object类型</param>
        /// </summary>
        public RegionEntity GetById(string id)
        {
            return this.GetById<RegionEntity>(id);

        }

        /// <summary>
        /// 通过编码查询区域
        /// </summary>
        public RegionEntity GetByCode(string regionCode)
        {
            ICriterion criter = Expression.And(Expression.Eq(RegionEntity.__RegionCode, regionCode), Expression.Eq(RegionEntity.__IsDeleted, false));
            return this.Select<RegionEntity>(criter);
        }

        /// <summary>
        /// 保存方法
        /// <param name="entity">对象</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Save(RegionEntity entity, ref string strError)
        {
            //if (Exist(entity.Name, entity.Id))
            //{
            //    strError = entity.OrgName + "已存在，请不要重复输入";
            //    return false;
            //}
            //if (string.IsNullOrWhiteSpace(entity.RegionId))
            //{
            //    entity.Id = MyGenerateHelper.GenerateOrder();
            //}
            // entity.OrgId = new WHLRDF.Application.BLL.SerialRuleService().CreateSerialNo(Organizations_Identity_Num, null, ref strError);// 主键生成值
            if (!string.IsNullOrWhiteSpace(entity.ParentCode))
            {
                var parent = this.GetByCode(entity.ParentCode);
                if (parent != null)
                {
                    entity.RegionPath = parent.RegionPath + "_" + entity.ParentCode;
                }
            }
            else
            {
                entity.RegionPath = "0";
            }
            return this.SaveOrUpdate<RegionEntity>(entity);

        }
        /// <summary>
        /// 删除方法
        /// <param name="deleteKey">主键，如果字符串请将字符串列表用单引号将字符串用上,如（'aaa','bbb'）</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Delete(string deleteKey, ref string strError)
        {
            if (!string.IsNullOrEmpty(deleteKey))
            {
                return this.Delete<RegionEntity>(deleteKey);
            }
            return true;
        }
        /// <summary>
        /// 分页查询方法
        /// <param name="grid">分页查询的相关参数</param>
        /// </summary>
        public LigerGrid ForGrid(LigerGrid ligerGrid)
        {
            ICriterion criter = Expression.Eq("IsDeleted", false);
            if (!string.IsNullOrEmpty(ligerGrid.keyWord))
            {
                criter = Expression.And(criter,

                           Expression.Like(new string[] {
                                RegionEntity._PrimaryKeyName ,
                                RegionEntity.__RegionName,
                                RegionEntity.__RegionNameEn,
                                RegionEntity.__RegionShortNameEn
                           }, ligerGrid.keyWord)
                           );
            }
            return this.Query<RegionEntity>(ligerGrid, criter);

        }
        #endregion

        #region 扩展方法
        /// <summary>
        /// 验证是否存在的方法
        /// <param name="name">需要验证的值</param>
        /// <param name="key">主键</param>
        /// </summary>
        public bool Exist(string name, string id)
        {
            id = (string.IsNullOrWhiteSpace(id)) ? "" : id;

            ICriterion criter = Expression.Eq("IsDeleted", false);
            criter =
                Expression.And(criter, Expression.And(Expression.Eq(RegionEntity.__RegionName, name),
                Expression.NotEq(RegionEntity._PrimaryKeyName, id))
                );
            var result = this.Query<RegionEntity>(criter).FirstOrDefault();
            return result != null;
        }
        #endregion

        #region 事件
        public bool CreateJson()
        {
           var lstAll= this.GetAll();
            string filePath = savePath;
            FileInfo info = new FileInfo(filePath);
            if (!info.Exists)
            {
                if (!info.Directory.Exists)
                {
                    info.Directory.Create();
                }
            }
            List<RegionEntity> regionEntities = new List<RegionEntity>();
            List<RegionEntity> regions = new List<RegionEntity>();
            regionEntities = lstAll.Where(x => string.IsNullOrWhiteSpace(x.ParentCode)).OrderBy(x => x.RegionOrder).ToList();
            regionEntities.ForEach(x => {
                regions.Add(x);
                //Dictionary<string, object> rootDic = new Dictionary<string, object>();
                //rootDic.Add(RegionEntity.__RegionCode,x.RegionCode);
                //rootDic.Add(RegionEntity.__RegionName, x.RegionName);
                //rootDic.Add(RegionEntity.__RegionNameEn, x.RegionNameEn);
                //rootDic.Add(RegionEntity.__RegionLevel,x.RegionLevel);
                //rootDic.Add(RegionEntity.__ParentCode, "");
                //rootDic.Add(RegionEntity.__RegionShortNameEn, x.RegionShortNameEn);
                x.ChildEntities = lstAll.Where(y => y.ParentCode == x.RegionCode).OrderBy(y => y.RegionOrder).ToList();
                if (x.ChildEntities != null && x.ChildEntities.Count > 0)
                {
                    //List<Dictionary<string, object>> lstTwoDic = new List<Dictionary<string, object>>();
                    x.ChildEntities.ForEach(k => {
                        //Dictionary<string, object> twoDic = new Dictionary<string, object>();
                        //twoDic.Add(RegionEntity.__RegionCode, k.RegionCode);
                        //twoDic.Add(RegionEntity.__RegionName, k.RegionName);
                        //twoDic.Add(RegionEntity.__RegionNameEn, k.RegionNameEn);
                        //twoDic.Add(RegionEntity.__RegionLevel, k.RegionLevel);
                        //twoDic.Add(RegionEntity.__ParentCode, k.ParentCode);
                        //twoDic.Add(RegionEntity.__RegionShortNameEn, k.RegionShortNameEn);
                        k.ChildEntities = lstAll.Where(n => n.ParentCode == k.RegionCode).OrderBy(n => n.RegionOrder).ToList();
                        if (k.ChildEntities != null && k.ChildEntities.Count > 0)
                        {
                            //List<Dictionary<string, object>> lstThreeDic = new List<Dictionary<string, object>>();
                            //foreach (var item in k.ChildEntities)
                            //{
                            //    Dictionary<string, object> threeDic = new Dictionary<string, object>();
                            //    threeDic.Add(RegionEntity.__RegionCode, item.RegionCode);
                            //    threeDic.Add(RegionEntity.__RegionName, item.RegionName);
                            //    threeDic.Add(RegionEntity.__RegionNameEn, item.RegionNameEn);
                            //    threeDic.Add(RegionEntity.__RegionLevel, item.RegionLevel);
                            //    threeDic.Add(RegionEntity.__ParentCode, item.ParentCode);
                            //    threeDic.Add(RegionEntity.__RegionShortNameEn,item.RegionShortNameEn);
                            //    lstThreeDic.Add(threeDic);
                            //}
                            //twoDic.Add("ChildEntities", lstThreeDic);
                        }
                        //lstTwoDic.Add(twoDic);
                    });
                   //rootDic.Add("ChildEntities", lstTwoDic);
                }
                //lstDic.Add(rootDic);
            });
            FileHelper.WriteLine( filePath, "var Global_Region_Data=" + regions.MapTo<List<RegionDto>>().ToJson());
            return true;
        }
        #endregion
    }
}